package com.aiti.lulian.service.impl;

import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.lulian.dto.LuLianOfferDto;
import com.aiti.lulian.entity.*;
import com.aiti.lulian.entity.message.OfferMessage;
import com.aiti.lulian.mapper.ILuLianOfferMapper;
import com.aiti.lulian.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName LuLianOfferServiceImpl
 * @Description 报价表service实现类
 * @Author diaozhende
 * @Date 2024/6/19 0019 11:00
 */
@Service
public class LuLianOfferServiceImpl extends BaseSerivceImpl<ILuLianOfferMapper, LuLianOffer> implements ILuLianOfferService {
    @Autowired
    private ILuLianOfferMapper luLianOfferMapper;
    @Autowired
    private ILuLianOfferGoodsService luLianOfferGoodsService;
    @Autowired
    private ILuLianOfferAttachmentService luLianOfferAttachmentService;
    @Autowired
    private ILulianEnterpriseHistoryService enterpriseHistoryService;
    @Autowired
    private ILuLianSourcingDemandService sourcingDemandService;
    @Autowired
    private IOfferMessageService offerMessageService;
    @Autowired
    private ICorporateStrengthPicService corporateStrengthPicService;

    /**
     * 查询报价总数
     *
     * @param
     * @return int
     * @date 2024/6/21 0021 15:30
     * @author diaozhende
     */
    @Override
    public int queryTotalCount() {
        return super.count();
    }

    /**
     * 查询报价列表（条件、分页）
     *
     * @param
     * @date 2024/7/3 16:14
     * @author WongMZ
     */
    @Override
    public Map<String, Object> queryOfferListPage(Page<LuLianOffer> page, LuLianOfferDto luLianOfferDto) {
        Map<String, Object> map = new HashMap<>();

        List<LuLianOffer> offerList = luLianOfferMapper.queryOfferListPage(page, luLianOfferDto);

        List<LuLianOfferDto> dtoList = new ArrayList<>();
        for (LuLianOffer offer : Optional.ofNullable(offerList).orElse(new ArrayList<>())) {
            LuLianOfferDto offerDto = new LuLianOfferDto();
            BeanUtils.copyProperties(offer, offerDto);
            LuLianSourcingDemand demand = sourcingDemandService.getById(offer.getSourcingOrderId());
            if (demand != null) {
                offerDto.setSourcingOrderName(demand.getBaseName());
            }
            LambdaQueryWrapper<LuLianOfferGoods> offerGoodsWrapper = new LambdaQueryWrapper<>();
            offerGoodsWrapper.eq(LuLianOfferGoods::getOfferId, offer.getBaseId());
            List<LuLianOfferGoods> goodsList = luLianOfferGoodsService.list(offerGoodsWrapper);
            offerDto.setGoodsOfferList(goodsList);
            LambdaQueryWrapper<LuLianOfferAttachment> offerAttachmentWrapper = new LambdaQueryWrapper<>();
            offerAttachmentWrapper.eq(LuLianOfferAttachment::getOfferId, offer.getBaseId());
            List<LuLianOfferAttachment> attachmentList = luLianOfferAttachmentService.list(offerAttachmentWrapper);
            offerDto.setFileList(attachmentList);
            dtoList.add(offerDto);
        }

        map.put("total", page.getTotal());
        map.put("list", dtoList);

        return map;
    }

    @Override
    public Map<String, Object> queryCount(String offerUserId) {
        Map<String, Object> map = new HashMap<>();

        //报价记录总数
        long totalCount = luLianOfferMapper.selectTotalCount(offerUserId);
        //交易成功记录总数
        long successCount = luLianOfferMapper.selectSuccessCount(offerUserId);
        //成交总金额
        BigDecimal successAmount = luLianOfferMapper.selectAuccessAmount(offerUserId);
        if (successAmount == null) {
            successAmount = new BigDecimal(0.00);
        }
        //长期有效类型下的报价记录数
        long longTermAmount = luLianOfferMapper.selectLongTerm(offerUserId);
        //自定义时间类型下且在有效期内的报价记录数
        long customInValidityPeriodCount = luLianOfferMapper.selectInValidityPeriodCount(offerUserId);
        //有效期内的报价记录总数
        long inValidityPeriodCount = longTermAmount + customInValidityPeriodCount;
        //已报价状态的报价记录总数
        long offeredCount = luLianOfferMapper.selectOfferStatusCount(offerUserId, "0");
        //已撤回状态的报价记录总数
        long withdrawnCount = luLianOfferMapper.selectOfferStatusCount(offerUserId, "1");
        //被退回状态的报价记录总数
        long backedCount = luLianOfferMapper.selectOfferStatusCount(offerUserId, "2");

        map.put("totalCount", totalCount);
        map.put("successCount", successCount);
        map.put("successAmount", successAmount);
        map.put("inValidityPeriodCount", inValidityPeriodCount);
        map.put("offeredCount", offeredCount);
        map.put("withdrawnCount", withdrawnCount);
        map.put("backedCount", backedCount);

        return map;
    }

    @Override
    public boolean updateOfferByBaseId(LuLianOffer luLianOffer) {
        return luLianOfferMapper.updateOfferByBaseId(luLianOffer);
    }

    @Transactional
    @Override
    public int saveOffer(LuLianOfferDto luLianOfferDto) {
        LuLianOffer offer = new LuLianOffer();
        BeanUtils.copyProperties(luLianOfferDto, offer);
        boolean res1 = this.save(offer);

        List<CorporateStrengthPic> corporateStrength = luLianOfferDto.getCorporateStrength();
        if (corporateStrength != null && corporateStrength.size() > 0) {
            // 存储企业实力图片
            List<CorporateStrengthPic> corporateStrengthPicList = corporateStrength.stream().peek(i -> {
                i.setId(offer.getBaseId());
                i.setType("1");
            }).collect(Collectors.toList());
            corporateStrengthPicService.saveBatch(corporateStrengthPicList);
        }

        List<LuLianOfferGoods> goodsOfferList = luLianOfferDto.getGoodsOfferList();
        if (goodsOfferList != null && goodsOfferList.size() > 0) {
            // 存储报价商品
            for (LuLianOfferGoods offerGoods : goodsOfferList) {
                offerGoods.setOfferId(offer.getBaseId());
                boolean res2 = luLianOfferGoodsService.save(offerGoods);
                if (! res2){
                    return 0;
                }
            }
        }

        List<LuLianOfferAttachment> fileList = luLianOfferDto.getFileList();
        if (fileList != null && fileList.size() > 0) {
            for (LuLianOfferAttachment offerAttachment : fileList) {
                offerAttachment.setOfferId(offer.getBaseId());
                boolean res3 = luLianOfferAttachmentService.save(offerAttachment);
                if (! res3){
                    return 0;
                }
            }
        }

        if (res1){
            OfferMessage message = new OfferMessage();
            message.setOfferUserId(luLianOfferDto.getOfferUserId());

            Map<String, String> resMap = enterpriseHistoryService.queryEnterpriseIdAndName(luLianOfferDto.getOfferUserId());
            if (resMap != null) {
                String enterpriseName =  resMap.get("basename");
                message.setEnterpriseName(enterpriseName);
            }

            message.setSourcingOrderId(luLianOfferDto.getSourcingOrderId());
            message.setOfferId(offer.getBaseId());

            LambdaQueryWrapper<LuLianSourcingDemand> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(LuLianSourcingDemand::getBaseId, luLianOfferDto.getSourcingOrderId());
            LuLianSourcingDemand sourcingDemand = sourcingDemandService.getOne(wrapper);
            message.setSourcingOrderUserId(sourcingDemand.getCreator());
            message.setSourcingOrderName(sourcingDemand.getBaseName());

            boolean res = offerMessageService.save(message);
            if (! res) {
                return -1;
            }

            return 1;
        }
        return 0;
    }
}